﻿using Account.Api.Client;
using BlazorDownloadFile;
using Blazored.LocalStorage;
using Common.Api.Client;
using Cyss.Core;
using Cyss.Core.Api.Client;
using Cyss.Core.Infrastructure;
using CyssBlazor.Shared.Components;
using CyssBlazor.Shared.Infrastructure;
using CyssBlazor.WebAssembly.Infrastructure;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Order.Api.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;

namespace CyssBlazor.WebAssembly
{
    public static class ServicesExtensions
    {
        public static async Task<IServiceCollection> AddWasmServices(this WebAssemblyHostBuilder builder)
        {
            //System.Globalization.CultureInfo.DefaultThreadCurrentCulture = new System.Globalization.CultureInfo("zh-CN", true)
            //{
            //    DateTimeFormat = { ShortDatePattern = "yyyy-MM-dd", FullDateTimePattern = "yyyy-MM-dd HH:mm:ss", LongTimePattern = "HH:mm:ss" },
            //};
            builder.Services.AddScoped<ModalService>();

            builder.Services.AddBlazoredLocalStorage(config =>
                 config.JsonSerializerOptions.WriteIndented = true);

            // 添加本行代码
            builder.Services.AddBootstrapBlazor();

            // 增加 Table Excel 导出服务
            //builder.Services.AddBootstrapBlazorTableExcelExport();

            // 增加本地化服务
            //builder.Services.AddJsonLocalization();

            builder.Services.AddBlazorDownloadFile(ServiceLifetime.Scoped);

            //注册记录日志
            // builder.Services.AddSingleton<ILoggingApi, ClientLoggingApi>();
            ///加载配置
            await LoadConfig(builder);

            //注册api客户端
            builder.Services.AddSingleton<IApiToken, ApiToken>();
            builder.Services.RegisterAccountClient();
            builder.Services.RegisterCommonClient();
            builder.Services.RegisterOrderClient();


            builder.Services.AddScoped<DialogHelper>();
            builder.Services.AddSingleton<IIOCCore, IOCCore>();

            builder.Services.AddSingleton<BootstrapBlazor.Components.MessageService>();

            builder.Services.AddScoped<IUserAuthenService, UserAuthenService>();
            builder.Services.AddScoped<IUserAuthStateProvider, UserAuthStateProvider>();

            builder.Services.AddScoped<IBlazorWorkContext, BlazorWorkContext>();


            //在wasm中没有默认配置，所以需要设置一下
            builder.Services.AddAuthorizationCore();



            return builder.Services;
        }

        /// <summary>
        /// 加载配置
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        private static async Task LoadConfig(WebAssemblyHostBuilder builder)
        {
            //加载配置
            try
            {
                var httpClient = new HttpClient();
                httpClient.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress);
                var apiResponseAssemblie = await httpClient.PostReceiveResponeObject<IEnumerable<string>>($"Config/GetAssemblies?v={DateTime.Now.ToFileTimeUtc()}", null);
                if (apiResponseAssemblie.IsSuccess == false) return;
                var apiResponse = await httpClient.PostReceiveResponeObject<Dictionary<string, object>>($"Config/GetConfig?v={DateTime.Now.ToFileTimeUtc()}", null);
                if (apiResponse.IsSuccess == false) return;

                List<Type> BaseConfigTypes = new List<Type>();
                foreach (var assemblyName in apiResponseAssemblie.Data)
                {
                    try
                    {
                        var assembly = Assembly.Load(assemblyName);
                        BaseConfigTypes.AddRange(assembly.GetTypes().Where(t => t.IsInterface == false && t.GetInterfaces().Contains(typeof(BaseConfig))));
                    }
                    catch (Exception ex)
                    {
                        ExceptionHelper.AddError(assemblyName, "assemblyName");
                    }
                }
                foreach (var type in BaseConfigTypes)
                {
                    if (apiResponse.Data.ContainsKey(type.Name) == false) continue;
                    var config = JsonHelper.DeserializeObject(apiResponse.Data[type.Name].ToSerializeObject(), type) as BaseConfig;
                    ConfigCore.AddConfig(config);
                    ExceptionHelper.AddError(config.ToSerializeObject(), type.Name);
                    builder.Services.AddSingleton(type, config);
                }

            }
            catch (Exception ex)
            {
                ExceptionHelper.AddError("加载配置失败", "Exception");
            }

        }



    }
}
